using System;
using System.Reflection;

namespace AGame.TabOrm.TabOrmAttributeExpand
{
    /// <summary>
    /// 自定义方法转换
    /// </summary>
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
    public class CustomTabField : TabField
    {
        public string StringToObjFunc;
        public string ObjToStringFunc;

        public CustomTabField(string stringToObjFunc, string objToStringFunc, string name = null) : base(name)
        {
            StringToObjFunc = stringToObjFunc;
            ObjToStringFunc = objToStringFunc;
        }

        public override Func<string, object> GetStrToObjFunc(Type tabType, Type targetType)
        {
            if (string.IsNullOrEmpty(StringToObjFunc))
            {
                return null;
            }
            var methodInfo = tabType.GetMethod(StringToObjFunc,
                BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.Public);
            if (methodInfo != null)
            {
                return s => methodInfo.Invoke(null, new object[] {s});
            }

            return null;
        }

        public override Func<object, string> GetObjToStrFunc(Type tabType, Type targetType)
        {
            if (string.IsNullOrEmpty(ObjToStringFunc))
            {
                return null;
            }
            var methodInfo = tabType.GetMethod(ObjToStringFunc,
                BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.Public);
            if (methodInfo != null)
            {
                return s => methodInfo.Invoke(null, new[] {s})?.ToString();
            }
            return null;
        }
    }
}